﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using RuanRang.Media.Core.Internal.DataStructures;
using RuanRang.Media.Core.Internal.Interop;

namespace RuanRang.Media.Core.Media
{
    ///<summary>
    /// VlcMediaTrackInfos class
    ///</summary>
    public sealed class VlcMediaTrackInfo : IEnumerable<libvlc_media_track_info_t>
    {
        /// <summary>
        /// The _my media base
        /// </summary>
        private readonly BaseMedia _myHostMediaBase;
        /// <summary>
        /// VlcMediaTrackInfos constructor
        /// </summary>
        internal VlcMediaTrackInfo(BaseMedia mediaBase)
        {
            _myHostMediaBase = mediaBase;
        }

        /// <summary>
        /// Returns the collection of media track informations
        /// </summary>
        /// <returns>Media track informations</returns>
        public IEnumerator<libvlc_media_track_info_t> GetEnumerator()
        {
            if (!LibVlcMediaInterop.libvlc_media_is_parsed(_myHostMediaBase.Handle))
            {
                LibVlcMediaInterop.libvlc_media_parse(_myHostMediaBase.Handle);
            }
            IntPtr mediaInfoPtr;
            var count =LibVlcMediaInterop.libvlc_media_get_tracks_info(_myHostMediaBase.Handle, out mediaInfoPtr);
            try
            {
                if (count <= 0) yield break;
                var currentMediaTrackInfosPtr = mediaInfoPtr;
                var size = Marshal.SizeOf(typeof(libvlc_media_track_info_t));
                if (currentMediaTrackInfosPtr == IntPtr.Zero) yield break;
                for (var i = 0; i < count; i++)
                {
#if SILVERLIGHT
                                var mediaTrackInfos = new MediaTrackInfo();
                                Marshal.PtrToStructure(currentMediaTrackInfosPtr, mediaTrackInfos);
                                yield return mediaTrackInfos;
#else
                    yield return (libvlc_media_track_info_t)Marshal.PtrToStructure(currentMediaTrackInfosPtr,typeof(libvlc_media_track_info_t));
#endif
                    currentMediaTrackInfosPtr = new IntPtr(currentMediaTrackInfosPtr.ToInt64() + size);
                }
            }
            finally
            {
                LibVlcMediaInterop.libvlc_free(mediaInfoPtr);
            }
        }

        /// <summary>
        /// Returns the collection of media track informations
        /// </summary>
        /// <returns>Media track informations</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
           return GetEnumerator();
        }
    }
}
